// 退款成功页面
import React, {Component} from 'react';
import {StatusBar, Text, View, TouchableWithoutFeedback, TouchableOpacity, StyleSheet} from 'react-native';
import CXIcon from '../../../style/icon/CXIcon';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import storeActions from '../../../store/actions/store';
import {bindActionCreators} from 'redux';
import {Actions} from "react-native-router-flux";
import {connect} from "react-redux";
import {fen_to_yuan} from "../../../utils";
import Tips from "react-native-root-tips";
import {RNUSBPrinter} from "react-native-usb-printer-mi";
const Buffer = require('buffer').Buffer;
class returnSuccess extends Component {
    constructor(props) {
        super(props);
        this.state = {
            info: {
                refund: {
                    user: '',
                    payment: [],
                    clerk: ''
                },
                exchangeOrder: ''
            },
            isPrint: false
        }
    }

    componentDidMount = async () => {
        const devices = await RNUSBPrinter.getUSBDeviceList();
        if (devices && devices.length) {
            let vendorId = '';
            let productId = '';
            let isPrint = false;
            let printedSelected = '';
            devices.forEach(item => {
                if (item.device_type == 7) {
                    vendorId = item.vendor_id;
                    productId = item.product_id;
                    isPrint = true;
                    this.setState({
                        isPrint: isPrint
                    })
                }
            });
            if (isPrint) {
                printedSelected = await RNUSBPrinter.connectPrinter(vendorId, productId);
            }
            this.setState(Object.assign({}, this.state, {
                printedSelected: printedSelected,
                devices: devices,
            }));
        }
        let {storeAction} = this.props;
        storeAction.refundSuccessInfo(this.props.refund_id || 65, (res) => {
            if (res && res.status && res.data) {
                this.setState({
                    info: res.data
                })
            }
        });
        this.setState({
            order_no: this.props.order_no
        })
    };
    // 打印单据
    printOrder() {
        if(this.state.printedSelected) {
            let {storeAction} = this.props;
            /*if (!this.props.refund_id) {
                Tips.showFail('订单号错误');
                return
            }*/
            storeAction.getRefundPrintInfo(this.props.refund_id || 65, res => {
                if (res.status) {
                    let arr = [];
                    Object.keys(res.data).forEach((v) => {
                        if (v !== 'logo' && v !== 'qrcode') {
                            res.data[v] = res.data[v].map((h) => {
                                return parseInt(h, 16)
                            })
                        }
                        arr.push(...res.data[v])
                    });
                    console.log('这个是之前的', arr);
                    var typedArray = new Buffer(arr);
                    console.log('获取到的', typedArray);
                    RNUSBPrinter.printTextCut(typedArray);
                }
            });
        }else{
            Tips.showFail('打印机未连接或者未授权');
        }
    }

    //查看订单性情
    _clickOrderDetail() {
        Actions.push('BalanceOrderPage', {
            order_no: this.props.order_no
        })
    }

    //点击继续收银
    _clickIndexPage(){
        Actions.reset('IndexPage')
    }

    //渲染支付方式
    _renderPayments(payments){
        return payments.map((item,index) =>{
            if (item.origin_type != 'order') {
                return (
                    <Text style={[index == 0 ? style.paymentsLast : '']} key={index}>
                        {item.origin_type_text}
                    </Text>
                )
            }
        })
    }

    // 换货Node
    _refundTypeNode() {
        if (this.state.info.refund.type == 2) {
            return (
                <View style={{flexDirection: 'row', justifyContent: 'center'}}>
                    <Text style={[style.miniTitle, {paddingRight: 37}]}> 退货金额：¥ {fen_to_yuan(this.state.info.refund.amount)}</Text>
                    <Text style={style.miniTitle}> 换货金额： ¥ {fen_to_yuan(this.state.info.exchangeOrder.total)}</Text>
                </View>
            )
        }
    }

    //渲染整个页面
    _renderPage() {
        /*let{storeState} = this.props;*/
        if (1) {
            return (
                <View style={style.page}>
                    <StatusBar hidden={true}/>
                    <Text style={style.title}>
                        退款完成 ¥ {fen_to_yuan(this.state.info.refund.actual_amount)}
                    </Text>
                    {this._refundTypeNode()}
                    <View style={style.infoBox}>
                        <View style={style.infoItem}>
                            <Text style={{flex: 1}}>
                                售后编号：{this.state.info.refund.refund_no}
                            </Text>
                            <Text>
                                时间：{this.state.info.refund.created_at}
                            </Text>
                        </View>
                        <View style={style.infoItem}>
                            <View style={{flexDirection: 'row', flex: 1}}>
                                <Text style={{marginRight: 100}}>
                                    会员：{this.state.info.refund.user.nick_name} {this.state.info.refund.user.mobile}
                                </Text>
                                <Text>
                                    导购：{this.state.info.refund.clerk.name}
                                </Text>
                            </View>
                            <TouchableWithoutFeedback>
                                <View style={style.noteBox}>
                                    <CXIcon name='beizhu' color='#909090' size={20}></CXIcon>
                                    <Text style={{marginLeft: 10}} numberOfLines={1}>理由: {this.state.info.refund.content}</Text>
                                </View>
                            </TouchableWithoutFeedback>

                        </View>
                        <View style={style.infoItem}>
                            <Text style={{flex: 1}}>
                                共{this.state.info.refund.quantity || 0}件
                            </Text>
                            <View style={style.itemLeft}>
                                <Text style={{marginRight: 50}}>
                                    退款方式：{this._renderPayments(this.state.info.refund.payment)}
                                </Text>

                                <Text>
                                    退款总额：¥{fen_to_yuan(this.state.info.refund.actual_amount)}
                                </Text>
                            </View>
                        </View>
                    </View>

                    <View style={style.bottomBox}>
                        <TouchableWithoutFeedback onPress={() => this._clickIndexPage()}>
                            <View style={[style.btn, {marginRight: 80, backgroundColor: '#909090'}]}>
                                <Text style={style.btnText}>
                                    继续收银
                                </Text>
                            </View>
                        </TouchableWithoutFeedback>

                        <TouchableWithoutFeedback onPress={() => this.printOrder()}>
                            <View style={style.btn}>
                                <Text style={style.btnText}>
                                    打印收据
                                </Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
                </View>
            )
        }
    }

    render() {
        return (
            <View>
                {this._renderPage()}
            </View>
        )
    }
}

const style = StyleSheet.create({
    page: {
        backgroundColor: white,
        height: '100%',
        alignItems: 'center'
    },
    title: {
        fontSize: 38,
        color: '#F58B23',
        textAlign: 'center',
        marginTop: 110,
        marginBottom: 20
    },
    miniTitle: {
        color: mainBackgroundColor,
        fontSize: 16
    },
    infoBox: {
        width: 900,
        marginTop: 40,
    },
    infoItem: {
        flexDirection: 'row',
        // alignItems: 'center',
        padding: 20,
        borderTopWidth: 1,
        borderColor: '#DBDBDB'
    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    noteBox: {
        width: 175,
        flexDirection: 'row'
    },
    bottomBox: {
        position: 'absolute',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        left: 0,
        right: 0,
        bottom: 0,
        height: 90,
        borderTopWidth: 1,
        borderTopColor: '#DBDBDB'
    },
    btn: {
        width: 160,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 4,
        backgroundColor: mainBackgroundColor
    },
    btnText: {
        color: white
    }
});


export default connect(state => ({
    storeState: state.store
}), dispatch => ({
    storeAction: bindActionCreators(storeActions, dispatch)
}))(returnSuccess);
